import type {
  PositionSchema,
  PositionAnalysisGroupSchema,
  PositionAnalysisSchema
} from "@/types/account.types";
import { ref } from "vue";

/**
 * 持仓分组、统计delta
 */
export const usePositionAnalyzing = () => {
  const isFilterOnlyFutures = ref(false);

  const analyzePosition = (
    position: PositionSchema[]
  ): PositionAnalysisGroupSchema[] => {
    if (!Array.isArray(position) || position.length === 0) return [];

    const grouped = new Map<string, PositionSchema[]>();
    for (const p of position) {
      const key = p.underlying_symbol || "";
      const arr = grouped.get(key) || [];
      arr.push(p);
      grouped.set(key, arr);
    }

    const rankProductType = (t?: string) => {
      if (t === "期货") return 0;
      if (t === "期权") return 1;
      return 2;
    };

    const groups: PositionAnalysisGroupSchema[] = [];

    for (const [underlying, items] of grouped) {
      const children: PositionAnalysisSchema[] = items
        .map(p => {
          const gammaValue = p.gamma ?? 0;
          const isLong = p.direction === "多";
          return {
            underlying_symbol: "",
            product_type: p.product_type,
            symbol: p.symbol,
            direction: p.direction,
            volume: p.volume,
            cost: p.cost,
            last_price: p.last_price,
            pnl_by_cost: p.pnl_by_cost ?? 0,
            delta: p.delta ?? 0,
            long_gamma: isLong ? gammaValue : undefined,
            short_gamma: !isLong ? gammaValue : undefined,
            option_market_value: p.option_market_value ?? 0,
            option_intrinsic_value: p.option_intrinsic_value ?? 0,
            option_time_value: p.option_time_value ?? 0,
            option_underlying_last_price: p.option_underlying_last_price
          } as PositionAnalysisSchema;
        })
        .sort((a, b) => {
          const ra = rankProductType(a.product_type);
          const rb = rankProductType(b.product_type);
          if (ra !== rb) return ra - rb;
          const sa = a.symbol || "";
          const sb = b.symbol || "";
          return sa.localeCompare(sb);
        });

      const summary = children.reduce(
        (acc, cur) => {
          acc.delta += (cur.delta || 0) * cur.volume;
          acc.pnl_by_cost += cur.pnl_by_cost || 0;
          acc.long_gamma =
            (acc.long_gamma || 0) + (cur.long_gamma || 0) * (cur.volume || 0);
          acc.short_gamma =
            (acc.short_gamma || 0) + (cur.short_gamma || 0) * (cur.volume || 0);
          acc.option_market_value += cur.option_market_value || 0;
          acc.option_intrinsic_value += cur.option_intrinsic_value || 0;
          acc.option_time_value += cur.option_time_value || 0;
          return acc;
        },
        {
          underlying_symbol: underlying,
          delta: 0,
          pnl_by_cost: 0,
          long_gamma: 0,
          short_gamma: 0,
          option_market_value: 0,
          option_intrinsic_value: 0,
          option_time_value: 0
        } as PositionAnalysisSchema
      );

      const group: PositionAnalysisGroupSchema = {
        ...summary,
        product_type: undefined,
        symbol: undefined,
        direction: undefined,
        volume: undefined,
        cost: undefined,
        is_summary_row: true,
        children
      };

      groups.push(group);
    }

    groups.sort((a, b) =>
      a.underlying_symbol.localeCompare(b.underlying_symbol)
    );

    if (isFilterOnlyFutures.value) {
      // Keep groups that are NOT composed solely of futures (i.e., have any non-futures child)
      return groups.filter(g =>
        g.children.some(c => c.product_type !== "期货")
      );
    }

    return groups;
  };

  return {
    isFilterOnlyFutures,
    analyzePosition
  };
};
